#!/bin/bash
clean() {
	FILE_NAME=${1%.*}
    fm_list="320x180_500k 640x360_750k 640x360_1000k 1280x720_1500k"
    for item in ${fm_list[@]};do
        [ -e ${FILE_NAME}_video_${item}.mp4 ] && rm ${FILE_NAME}_video_${item}.mp4
        [ -e ${FILE_NAME}_video_${item}_f.mp4 ] && rm ${FILE_NAME}_video_${item}_f.mp4
    done
    [ -e ${FILE_NAME}_audio_128k.mp4 ] && rm ${FILE_NAME}_audio_128k.mp4
    [ -e ${FILE_NAME}_audio_128k_f.mp4 ] && rm ${FILE_NAME}_audio_128k_f.mp4
    [ -e output ] && rm -rf output
}

dash_file() {
	FILE_NAME=${1%.*}
    fm_list="320x180_500k 640x360_750k 640x360_1000k 1280x720_1500k"
    if [ ! -e ${FILE_NAME}.mp4 ]; then
        echo "${FILE_NAME}.mp4 not exists"
        exit 1
    fi

    begin=`date +%s`
    echo "------------------------------------------------------"
    for item in ${fm_list[@]};do
    {
#        echo ${item}  ${item%_*} ${item#*_}
#        echo "ffmpeg -i ${FILE_NAME}.mp4 -s ${item%_*} -c:v libx264 -b:v ${item#*_} -g 90 -an ${FILE_NAME}_video_${item}.mp4"
        ffmpeg -i ${FILE_NAME}.mp4 -s ${item%_*} -c:v libx264 -b:v ${item#*_} -g 90 -an ${FILE_NAME}_video_${item}.mp4
    }
#&
    done
#    wait
    ffmpeg -i ${FILE_NAME}.mp4 -c:a aac -b:a 128k -vn ${FILE_NAME}_audio_128k.mp4
    echo "------------------------------------------------------"
    end=`date +%s`
    echo -e "\033[47;30mdecoe video spend $((end-begin))s\033[0m"
    for item in `ls ${FILE_NAME}*k.mp4`;do
        mp4fragment ${item} ${item%.*}_f.mp4
    done
    mp4dash ${FILE_NAME}_*_f.mp4
}

if [ $# -lt 1 ];then
	echo "$0 input_file.mp4"
	exit 1
fi

clean ${1}
dash_file ${1}